// 读取json数据
const path = require('path')
const fs =require('fs')
const rootPath = process.cwd();
const store = {};

// 读取json
function loaderFile(path){
    return new Promise((resolve, reject) =>{
        fs.readFile(path, {encoding: 'UTF-8'}, (e, data) =>{

            if(e){
                reject(e)
                return;
            }

            store[path] = data;
            resolve(data)

        })  
    })
}

// 读取缓存
function loaderCache(path){
    return new Promise((resolve, reject) =>{
        resolve(store[path])
    })
}


function loaderData(fileName){

    const filePath = path.resolve(rootPath, `./db/${fileName}.json`);
    
    try{
        return store[filePath] ? loaderCache(filePath) : loaderFile(filePath); 
    }catch(error){
        console.error(`read json error \n filePath: ${filePath} \n ERROR: ${error}`)
    }

}

module.exports = loaderData;